var PATH_PREFIX ="";
var NAV_PATH_PREFIX ="";
var FEE_PATH_PREFIX ="";
var FEE_TYPE_PATH_PREFIX ="";
function setPathPrefix(path){
	PATH_PREFIX =  path;
}
function setNavPathPrefix(path){
	NAV_PATH_PREFIX =  path;
}
function setFeePathPrefix(path){
	FEE_PATH_PREFIX =  path;
}
function setFeeTypePathPrefix(path){
	FEE_TYPE_PATH_PREFIX =  path;
}

$(function() {
	// 给select2组件加载样式
	WASP_WIDGET.initializeSelectStyle();
	
	WASP_WIDGET.triggerDateRangeStyle("q-time");
	// 注册清空事件
    WASP_WIDGET.registerResetClearEvent();

    
    // 是否选中(样式切换)
    initChoose('riskLevel');
    initChoose('prdType');
    initChoose('prdTerm');
    
    var prdFlag = $("#prdFlag").val();
    if('HOT' == prdFlag){
    	$($("#allPrd",window.parent.document)).removeClass('active');
    	$($("#hotSale",window.parent.document)).addClass('active');
    }
    
    $('#t-prdTerm').hide();
});

function chooseUnlimitedType(){
	var attr = $('#unlimitedType').attr("class")
	if(attr.indexOf("checked") > -1){
		$('#unlimitedType').removeClass('checked');
		
	}else{
		$('#unlimitedType').addClass('checked');
		// 选中清空其他的选项
	    $('.prdType.fa-check-square').each(function(index,element){
	    	$(element).removeClass('fa-check-square');
			$(element).addClass('fa-square');
	    });
	}
}
// 
function chooseUnlimited(){
	var attr = $('#unlimited').attr("class")
	if(attr.indexOf("checked") > -1){
		$('#unlimited').removeClass('checked');
		
	}else{
		$('#unlimited').addClass('checked');
		// 选中清空其他的选项
	    $('.riskLevel.fa-check-square').each(function(index,element){
	    	$(element).removeClass('fa-check-square');
			$(element).addClass('fa-square');
	    });
	}
	/*var attr = $('#unlimited').attr("class");
	console.log("attr:"+attr);
	if(attr.indexOf("fa-square") > -1){
		$('#unlimited').removeClass('fa-square');
		$('#unlimited').addClass('fa-check-square');
		// 选中清空其他的选项
	    $('.riskLevel.fa-check-square').each(function(index,element){
	    	$(element).removeClass('fa-check-square');
			$(element).addClass('fa-square');
	    });
	}else{
		$('#unlimited').removeClass('fa-check-square');
		$('#unlimited').addClass('fa-square');
	}*/
}

function chooseOthersType(){
	var attr = $('#unlimitedType').attr("class");
	// 如果不限选中，则设置为不选中
	if(attr.indexOf("checked") > -1){
		$('#unlimitedType').removeClass('checked');
	}
}

function chooseOthers(){
	var attr = $('#unlimited').attr("class");
	// 如果不限选中，则设置为不选中
	if(attr.indexOf("checked") > -1){
		$('#unlimited').removeClass('checked');
	}
	// 如果不限选中，则设置为不选中
	/*if(attr.indexOf("fa-check-square") > -1){
		$('#unlimited').removeClass('fa-check-square');
		$('#unlimited').addClass('fa-square');
	}*/
}

// 清空 选中
function clearCondtion(){
	$('.fa-check-square').addClass('fa-square');
	$('.fa-check-square').removeClass('fa-check-square');
}

//是否选中(样式切换)
function initChoose(att){
    $('.'+att).on('click', function () {
    	var attr = $(this).attr("class");
    	if(attr.indexOf("fa-square") > -1){
    		$(this).removeClass('fa-square');
    		$(this).addClass('fa-check-square');
		}else{
			$(this).removeClass('fa-check-square');
    		$(this).addClass('fa-square');
		}
	});
}



var PRD_INFO = {
	prdInfoDetail : function(subPrdCode){
		var url = PATH_PREFIX + "goPrdInfoPage.do?method=detail&subPrdCode="+subPrdCode;
		window.open(url);
	},
	feeTypeManagement: function(){
		var url = FEE_TYPE_PATH_PREFIX + "treFeeTypeListView.do"
		window.open(url);
	},
	feeManagementAdd: function(){
		var url = FEE_PATH_PREFIX + "treFeeDetailView.do?type="
		window.open(url);
	},
	feeManagementDelete: function(){
		var url = FEE_PATH_PREFIX + "treFeeDetailDelete.do"
		window.open(url);
	},
	treNav: function(){
		var url = NAV_PATH_PREFIX+"navView.do";
		window.open(url);
	},
	addPrdLine: function(subPrdCode){
		var url = PATH_PREFIX + "addPrdInfo.do";
		window.open(url);
	},
	updateView: function(subPrdCode) {
    	window.open(PATH_PREFIX + "updateView.do?subPrdCode=" + subPrdCode);  
    },
    deleteDemand: function(subPrdCode) {
    	/** 删除 */
		ctools.confirm({title : "确认删除？", text: ""},
		function(isConfirm){
			if(isConfirm){
				$.ajax({
					type : "POST",
					dataType : "json",
					url : PATH_PREFIX + "delete.do",
					cache: false,
					data: {
						'subPrdCode': subPrdCode
					},
					success: function(data) {
						if (data.success) {
							swal(data.message, "", "success");
							queryByCondtion(false);
						} else {
							swal(data.message, "", "warning");
						}
					},
					error:function(xhr){
					   sweetAlertAjaxError(xhr);
					}
				});
			}
		});
    },
	download: function(subPrdCode) {
    	window.open(PATH_PREFIX + "download.do?subPrdCode=" + subPrdCode);
    },
	exportPrdInfo: function(){
		var name = $.trim($("#q-name").val()); 
//	    var publishTime = $.trim($("#q-time").getDateRangeValue()[0]);
		var startTime    = $("#q-time").getDateRangeValue()[0]; 
		var endTime    = $("#q-time").getDateRangeValue()[1]; 
	    var postData = $prdList.jqGrid("getGridParam", "postData");
	    
	    var prdTypes = getChosen('prdType');
	    var prdTerms = getChosen('prdTerm');
	    var riskLevels = getChosen('riskLevel');
	    
	    var prdFlag = $.trim($("#prdFlag").val());
	    
	    var urlParam ='&sp[prdsname]='+name
		+'&sp[startTime]='+startTime
		+'&sp[endTime]='+endTime
		+'&sp[prdTypes]='+prdTypes
		+'&sp[prdTerms]='+prdTerms
		+'&sp[riskLevels]='+riskLevels
		+'&sp[prdFlag]='+prdFlag;
	    
	    var actionUrl = PATH_PREFIX + "prdInfoExportTo.do?"+urlParam;
//		openDialog(actionUrl);
	    window.open(actionUrl);
	}
};

var $prdList = $('#prdInfoList');
var $gridparents = $("#myTabContent");//基于哪个父级元素使jqgrid自适应宽度，主要解决tab标签切换隐藏的列表宽度不对的问题
$(function() {
	// 市场观点
	$prdList.jqGrid({   
		url:PATH_PREFIX+'prdInfoListPage.do',
		mtype:'POST',
		//caption:'招商财富产品列表<button type="button" class="btn btn-default btn-sm btn-small btn-fullscreen" title="" tabindex="-1"><i class="fa fa-arrows-alt icon-fullscreen"></i></button>',  
		datatype: "json",
		colNames:["产品编码","产品名称","产品类型","期限(年)","规模(元)","风险等级","操作"],
		colModel:[  { name: 'subPrdCode', index: 'subPrdCode', key: true, width: 30, resizable: true, sortable: false },       
		            { name: 'subFundSname', index: 'subFundSname', width: 30, resizable: true, sortable: false },
		            { name: 'prdCategoryNM', index: 'prdCategoryNM', width: 30, resizable: true, sortable: false },
		            { name: 'prdTerm', index: 'prdTerm', width: 30, resizable: true, sortable: false },
		            { name: 'expectedRaiseAmt', index: 'prdScale', width: 30, resizable: true, sortable: false },
		            { name: 'prdRiskLevelMN', index: 'riskLevelNM', width: 30, resizable: true, sortable: false },
		            { name: 'option', index: 'option', width: 60, resizable: true, sortable: false }
				  ],
		rowNum: 20,
        rowList: [20, 30, 50],
        rownumbers: true,
        rownumWidth: 50,
        prmNames: { search: "search", page: "pageNo", rows: "limit" },
        height: 'auto',
        width: false,
        autowidth:true,
        editurl: '',
        viewrecords: true,
        cellEdit: false,
        shrinkToFit: true,
        grouping: false,
        jsonReader: {
            root: "items", //结果集
            records: "total", //总记录数 
            total: "pageCount", //总页数
            page: "pageNo", //当前页 
            repeatitems: false // (4) 
        },  
        postData: {
        	'sp[prdFlag]': $.trim($("#prdFlag").val())
        },
		multiselect:false,
		pager: "#prdInfoListPage",					
		viewrecords: true,
		hidegrid: false, 
		gridComplete: function(){
			var ids = $prdList.jqGrid('getDataIDs');
			for(var i=0;i < ids.length;i++){
				var rowId = ids[i];
				var rowData = $prdList.jqGrid('getRowData', rowId); 
				var params = {
						'detail': 'prdInfoDetailTemp',
						'update': 'templateUpdateTemp',
						'download': 'templateDownloadTemp',
						'del': 'templateDeleteTemp',
					};
				var permissionButton = Permission_Button.configPermissionButton(params);
				permissionButton.detail = Permission_Button.clickPermissionButton('prdInfoDetailTemp',"PRD_INFO.prdInfoDetail('" + rowData.subPrdCode + "');");
				permissionButton.update = Permission_Button.clickPermissionButton('templateUpdateTemp',"PRD_INFO.updateView('" + rowData.subPrdCode + "');");
				permissionButton.download = Permission_Button.clickPermissionButton('templateDownloadTemp',"PRD_INFO.download('" + rowData.subPrdCode + "');");
				permissionButton.del = Permission_Button.clickPermissionButton('templateDeleteTemp',"PRD_INFO.deleteDemand('" + rowData.subPrdCode + "');");

                $prdList.jqGrid('setRowData', ids[i], { option: Permission_Button.linkAllBtn(permissionButton)});
			}	
		}
	});
	$prdList.navGrid('#prdListPage',{edit:false,add:false,del:false,search:false,refreshstate:'current'});
	$prdList.jqGrid('setFrozenColumns');
	jqGridResize($prdList);
	
});

//绑定回车事件,查询
$("body").keypress(function(event){
	var key = event.which;
	if(key == "13"){
		queryByCondtion(true);
	}
});

// 获取选中的值
function getChosen(element){
	var data = '';
	//遍历
    $('.'+element+'.fa-check-square').each(function(index,element){
    	data += $(element).attr("value")+',';
    });
    if(data.length > 0){
    	data = data.substr(0,data.length-1);
    }
    return data;
}

function queryByCondtion(flag) {
    var name = $.trim($("#q-name").val());
    var prdFlag = $.trim($("#prdFlag").val());
//    var publishTime = $.trim($("#q-time").getDateRangeValue()[0]);
    var startTime    = $("#q-time").getDateRangeValue()[0]; 
	var endTime    = $("#q-time").getDateRangeValue()[1];
    var postData = $prdList.jqGrid("getGridParam", "postData");
    
    var prdCategorys = getChosen('prdType');
    var prdTerms = getChosen('prdTerm');
    var riskLevels = getChosen('riskLevel');
	$.extend(postData, {
		'sp[subFundSname]':name,
		'sp[startTime]':startTime,
		'sp[endTime]':endTime,
		'sp[prdCategorys]':prdCategorys,
		'sp[prdTerms]':prdTerms,
		'sp[riskLevels]':riskLevels,
		'sp[prdFlag]':prdFlag
	});
	console.log(postData);
    if (flag) {
    	$prdList.trigger("reloadGrid", [{ page: 1 }]); //重新载入Grid表格
    } else {
    	$prdList.trigger("reloadGrid"); //重新载入Grid表格
    }
};





